/**
 * Created by li-rz on 16-12-3.
 */

import './PersonalHeader.scss';
import Popup from "../../../both/Popup/Popup.jsx"
import PersonalCard from "../PersonalCard/PersonalCard.jsx"

import React from 'react';

function getCookie(name)
{
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}

function setCookie(name,value)
{
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}

function delCookie(name)
{
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=getCookie(name);
    if(cval!=null)
        document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}

class PersonalHeader extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
            modalState : false,
            email : "",
            password : "",
            st : ""
        }
    }

    /**
     *
     * @param event {Event}
     */
    submitSearch(event) {
        event.preventDefault();

        if(this.state.st !== ""){
            location.href = "/courses?st=" + this.state.st
        }
    }

    /**
     *
     * @param event {Event}
     */
    handleLogin(event) {
        event.preventDefault()

        // 如果已经登录，则是注销
        if(this.props.logined){
            delCookie("LoginToken")
            location.href = location.href.replace(/\#.*/,"")
        }else{
            this.setState({
                modalState : true
            })
        }
    }

    hideModal(){
        this.setState({
            modalState : false
        })
    }

    goRegister(){
        this.hideModal()
        var $ = jQuery
        var $target = $("#register");
        $target = $target.length && $target || $('[name=' + "register" + ']');
        if ($target.length) {
            var targetOffset = $target.offset().top;
            $('html,body').animate({
                    scrollTop: targetOffset
                },
                1000);
        }
    }

    changeInput(name,e){
        var change = {}
        change[name] = e.target.value
        this.setState(change)
    }

    submitLogin(e){
        e.preventDefault()

        var self = this
        if(self.state.email == "" || self.state.password == ""){
            toastr.warning("用户名或密码不能为空")
            return
        }
        fetch("/education/user/login",{
            method: 'POST',
            body:   JSON.stringify({
                email : self.state.email.trim(),
                password : self.state.password.trim()
            }),
            headers: { 'Content-Type': 'application/json' },
            credentials : "same-origin"
        })
            .then(res => res.json())
            .then(json => {
                if(json.status == 403){
                    toastr.error("用户名或密码错误")
                    return
                }

                var LoginToken = json.msg.LoginToken
                setCookie("LoginToken",LoginToken)
                toastr.success("登录成功")
                location.href = location.href.replace(/\#.*/,"")
            })
    }

    /**
     *
     * @returns {XML}
     */
    render() {
        const { reverse } = this.props
        const handleLogin = this.handleLogin.bind(this)
        const hideModal = this.hideModal.bind(this)
        const goRegister = this.goRegister.bind(this)
        const submitLogin = this.submitLogin.bind(this)
        const submitSearch = this.submitSearch.bind(this)

        return (
            <header className={reverse ? "reverse" : null}>
                <nav className="mooc-nav">
                    <div className="mooc-header-component mooc-logo-component">
                        <a className="href_cr" href="/">
                            <div className="mooc-logo"></div>
                            <span>OurEDA BAG</span>
                        </a>
                    </div>
                    <div className="mooc-header-component">
                        <ul className="mooc-header-list">
                            <li>
                                <a href="/courses">课程</a>
                            </li>
                            <li className="mooc-mobile-application">
                                <a href="javascript:void(0)">
                                    <i className="fa fa-mobile fa-2"></i><span>客户端</span>
                                </a>
                            </li>
                        </ul>
                    </div>
                    <div className="mooc-header-component mooc-login">
                        <div className="mooc-right mooc-search">
                            <form onSubmit={submitSearch}>
                                <input type="text" placeholder="搜索" value={this.state.st} onChange={this.changeInput.bind(this,"st")}/>
                                <i className="fa fa-search mooc-search-icon" onClick={submitSearch}/>
                            </form>
                        </div>
                        {
                            this.props.logined ?
                                <div className="mooc-right">
                                    <div className="mooc-welcome">
                                        欢迎&nbsp;{this.props.username}
                                    </div>
                                    <img className="mooc-avatar" src={this.props.avatar} />
                                    <PersonalCard avatar={this.props.avatar} username={this.props.username} handleLogin={handleLogin}/>
                                </div>: null
                        }
                        {
                            this.props.logined ? null : <div className="mooc-right mooc-login-event">
                                <a className="user_action" href="javascript:void(0)">
                                    <span onClick={handleLogin}>登录</span>
                                </a>
                                <a className="user_action" href="/#register">
                                    /&nbsp;&nbsp;<span>注册</span>
                                </a>
                            </div>

                        }
                    </div>

                    <Popup show={this.state.modalState} onCancel={hideModal} showCtrl={false} showHeader={false} title="登录" isFluid={true}>
                        <div className="login_header">
                            <div className="left">
                                <div className="logo"></div>
                                <span className="logo_name">BAG</span>
                                <span className="login_hint">&nbsp;登录</span>
                            </div>
                            <div className="right">
                                <div className="register_hint">还没有帐号？</div>
                                <div className="register_btn" onClick={goRegister}>快速注册</div>
                                <i className="fa fa-close" onClick={hideModal}/>
                            </div>
                        </div>
                        <div className="panel_body">
                            <form className="login_form" onSubmit={submitLogin}>
                                <div className="input_wr">
                                    <i className="fa fa-envelope" />
                                    <input type="text"
                                           name="email"
                                           className="login_input"
                                           value={this.state.email}
                                           onChange={this.changeInput.bind(this,"email")}
                                           placeholder="请输入登录邮箱"
                                    />
                                    <div className="input_border" />
                                </div>
                                <div className="input_wr">
                                    <i className="fa fa-key" />
                                    <input type="password"
                                           name="password"
                                           className="login_input"
                                           value={this.state.password}
                                           onChange={this.changeInput.bind(this,"password")}
                                           placeholder="6-16位密码"
                                    />
                                    <div className="input_border" />
                                </div>
                                <input type="submit" style={{display:"none"}}/>
                                <div type="submit" className="login_btn" onClick={submitLogin}>   /* todo: submit会影响颜色，应去掉*/
                                    登录
                                </div>
                            </form>
                        </div>
                    </Popup>
                </nav>
            </header>
        );
    }
}

PersonalHeader.PropTypes = {
    logined : React.PropTypes.bool,
    name: React.PropTypes.string,
    panel: React.PropTypes.string
};

PersonalHeader.defaultProps = {
    login: true
};

export default PersonalHeader;